/**
 * StringHelper
 *
 * Released under Apache License, Version 2.0.
 */

package bsp.helper;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class StringHelper
{
	protected StringHelper()
	{
		/* empty by design */
	}
	
	public static String freshSubstring(String s, int beginIndex, int endIndex)
	{
		return new String(s.substring(beginIndex, endIndex));
	}

	public static String freshSubstring(String s, int beginIndex)
	{
		return new String(s.substring(beginIndex));
	}
	
	public static String paddedSingleDigitInt2String(int c)
	{
		if ( c >= 10 ) {
			return String.valueOf(c);
		}
		
		return "0" + String.valueOf(c);
	}
	
	/**
	 * remove leading whitespace
	 */
    public static String ltrim(String source)
    {
    	return source.replaceAll("^\\s+", "");
    }

    /**
     * remove trailing whitespace
     */
    public static String rtrim(String source)
    {
    	return source.replaceAll("\\s+$", "");
    }

    /**
     * replace multiple white spaces between words with single blank
     */
    public static String itrim(String source)
    {
    	return source.replaceAll("\\b\\s{2,}\\b", " ");
    }

    /**
     * remove all superfluous white spaces in source string
     */
    public static String trim(String source)
    {
    	return itrim(ltrim(rtrim(source)));
    }

    /**
     * left and right trim the string.
     * 
     * @param source
     * @return
     */
    public static String lrtrim(String source)
    {
    	return ltrim(rtrim(source));
    }
	
	/**
	 * Compare two strings.
	 * 
	 * @param str1 - first string
	 * @param str2 - second string
	 * 
	 * @return Result of comparison. True or false
	 */
	public static boolean compareStrings(String str1, String str2)
	{
		if ( str1 == null || str2 == null ) {
			return false;
		}
		
		return str1.equals(str2);
	}
	
	/**
	 * 
	 * @param text String
	 * @param value String
	 * @return boolean
	 */
	public static boolean containsSubstring(String text, String value)
	{
		boolean ret = false;
		if ( text != null && value != null ) {
			int pos = text.indexOf(value);
			if ( pos == -1 ) {
				ret = false;
			} else {
				ret = true;
			}
		}
		
		return ret; 
	}
	
	/**
	 * 
	 * @param text String
	 * @param actualValue String
	 * @return boolean
	 */
	public static boolean containsSubstringIgnoreCase(String text, String actualValue)
	{
		boolean ret = false;
		if ( text != null && actualValue != null ) {
			// To ignore case, regular expressions must be used
			String m = "(?i).*" + actualValue + ".*";
			ret = text.matches(m);
		}
		
		return ret; 
	}

	/**
	 * 
	 * @param text String
	 * @param value2 String
	 * @return boolean
	 */
	public static boolean stringBeginsWith(String text, String actualValue)
	{
		boolean ret = false;
		if ( text != null && actualValue != null ) {
			// match case sensitive
			ret = text.startsWith(actualValue);
		}
		
		return ret; 
	}
	
	/**
	 * 
	 * @param text String
	 * @param value2 String
	 * @return boolean
	 */
	public static boolean stringBeginsWithIgnoreCase(String text, String actualValue)
	{
		boolean ret = false;
		if ( text != null && actualValue != null ) {
			// To ignore case, regular expressions must be used
			String m = "(?i)" + actualValue + ".*";
			ret = text.matches(m);
		}
		
		return ret; 
	}
	
	/**
	 * 
	 * @param str
	 * @return
	 */
	public static String removeNewlineUsingReader(String str)
	{
		String retVal = null;
		StringBuffer outStr = new StringBuffer(5000);
		
		try {
			StringReader sr = new StringReader(str);
			BufferedReader br = new BufferedReader(sr);
			
			while ( (str = br.readLine()) != null ) {
				outStr.append(str);
			}
			
			br.close();
			sr.close();
			retVal = outStr.toString();
		} catch ( Exception ex ) {
			ex.printStackTrace();
		}
		
		return retVal;
	}
	
	/**
	 * 
	 * @param str
	 * @return
	 */
	public static String removeSpaces(String str)
	{
		String retVal = null;
		StringTokenizer st = new StringTokenizer(str, " ", false);
		StringBuffer t = new StringBuffer(5000);
		while ( st.hasMoreElements() ) {
			t.append(st.nextElement());
		}
		
		retVal = t.toString();
		  
		return retVal;
	}
	
	/**
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBySingleSpace(String str)
	{
		String retVal = null;
		StringTokenizer st = new StringTokenizer(str, " ", false);
		StringBuffer t = new StringBuffer(5000);
		while ( st.hasMoreElements() ) {
			t.append(" ").append(st.nextElement());
		}
		  
		retVal = t.toString().trim();
		
		return retVal;
	}
	
	/**
	 * Split the input string into tokens, using a separator.
	 * 
	 * @param src Source string.
	 * @param separator Separator string.
	 * @return String[] Array of strings.
	 */
	public static String[] tokenize2StringArray(String src, String separator)
	{
		String[] arr = null;
		
		if ( separator == null ) {
			separator = " ";
		}
		
		if ( src != null ) {
			ArrayList<String> list = new ArrayList<String>();
			StringTokenizer tok = new StringTokenizer(src, separator);
			while ( tok.hasMoreTokens() ) {
				String str = tok.nextToken();
				if ( str != null ) {
					str = str.trim();
				}
				list.add(str);
			}
			
			int size = list.size();
			arr = new String[size];
			for ( int i = 0; i < size; i++ ) {
				arr[i] = new String((String)list.get(i));
			}
		}
		
		return arr;
	}
	
	/**
	 * This method can be used to convert an array of strings into a String object.
	 * 
	 * @param tok String array be converted.
	 * @param fieldSep Field separator.
	 * @return String
	 */
	public static String serializeStringArray(String[] tok, String fieldSep)
	{
		StringBuffer outStr = new StringBuffer(5000);
		
		if ( tok != null ) {
			for ( int i = 0; i < tok.length; i++ ) {
				if ( i > 0 ) {
					outStr.append(fieldSep);
				}
				
				outStr.append(tok[i]);
			}
		}
		
		String retVal = outStr.toString();
		return retVal;
	}
	
	/**
	 * Convert an array of String tokens into a single String.
	 * 
	 * @param tok Token array. Array of String.
	 * @param sep Seaprator.
	 * @param index Index to start from.
	 * @return String Array joined into a String.
	 */
	public static String createStringFromTokens(String[] tok, String sep, int index)
	{
		StringBuffer str = new StringBuffer(5000);
		
		if ( tok != null && tok.length > 0 ) {
			for ( int i = index; i < tok.length; i++ ) {
				if ( i > 0 ) {
					str.append(sep);
				}
				
				str.append(tok[i]);
			}
		}
		
		String retVal = str.toString();
		return retVal;
	}
	
	/**
	 * Convert a String into an array of integers.
	 * 
	 * @param src String to be converted.
	 * @param separator Separator.
	 * @return int[] Array of integers.
	 */
	public static int[] convertStringToIntegerArray(String src, String separator)
	{
		int[] tokenList = null;
		
		if ( src != null && separator != null ) {
			String[] tok = tokenize2StringArray(src, separator);
			tokenList = new int[tok.length];
			for ( int i = 0; i < tok.length; i++ ) {
				try {
					tokenList[i] = new Integer(tok[i]).intValue();
				} catch ( NumberFormatException ex ) {
					tokenList[i] = -1;
				}
			}
		}
		
		return tokenList;
	}
	
	/**
	 * Convert an array of integers into a String.
	 * 
	 * @param array Array of integers.
	 * @param separator Separator.
	 * @return String.
	 */
	public static String convertIntegerArrayToString(int[] array, String separator)
	{
		StringBuffer str = new StringBuffer(5000);
		
		if ( array != null && array.length > 0 ) {
			for ( int i = 0; i < array.length; i++ ) {
				if ( i > 0 ) {
					str.append(separator);
				}
				
				str.append(new Integer(array[i]).toString());
			}
		}
		
		String retVal = str.toString();
		return retVal;
	}
	
	/**
	 * Convert a token array into a token pair. In other words, take an array of tokens
	 * and return an array containing two tokens only. The first token is returned as is,
	 * but the remaining tokens are joined into one string.
	 * 
	 * @param src
	 * @param separator
	 * @return
	 */
	public static String[] convertTokenArray2TokenPair(String[] tokens, String separator)
	{
		String[] arr = null;
		
		if ( separator == null ) {
			separator = ",";
		}

		if ( tokens != null ) {
			arr = new String[2];
			arr[0] = new String(tokens[0]);
			int len = tokens.length;
			for ( int i = 1; i < len; i++ ) {
				if ( i == 1 ) {
					arr[1] = tokens[i];
				} else {
					arr[1] = arr[1] + separator + tokens[i];
				}
			}
		}
		
		return arr;
	}
	
	/**
	 * Take an input string and split it using the specified separator.
	 * Each token is then taken an quoted in the given quote mark,
	 * to construct final string.
	 * 
	 * @param data String - input data.
	 * @param separator String - input string separator.
	 * @param quote String - quote mark.
	 * @return String - quoted string.
	 */
	public static String quoteStringTokens(String data, String separator, String quote)
	{
		String[] sTok = StringHelper.tokenize2StringArray(data, separator);
		StringBuffer stemp = new StringBuffer(5000);
		for ( int i = 0; i < sTok.length; i++ ) {
			stemp.append(quote).append(sTok[i]).append(quote);
		}
		
		String retVal = stemp.toString();
		return retVal;
	}
	
	/**
	 * Take an input string and split it using the specified separator.
	 * Each token is then taken an quoted in the given quote mark,
	 * to construct final string. Original separator is retined.
	 * 
	 * @param data String - input data.
	 * @param separator String - input string separator.
	 * @param quote String - quote mark.
	 * @return String - quoted string.
	 */
	public static String quoteStringTokensWithSeparator(String data, String separator, String quote)
	{
		String[] sTok = StringHelper.tokenize2StringArray(data, separator);
		StringBuffer stemp = new StringBuffer(5000);
		for ( int i = 0; i < sTok.length; i++ ) {
			if ( i > 0 ) {
				stemp.append(separator);
			}
			
			stemp.append(quote).append(sTok[i]).append(quote);
		}
		
		String retVal = stemp.toString();
		return retVal;
	}
	
	/**
	 * 
	 * @param token
	 * @param exclude
	 * @param value
	 * @return
	 */
	public static String getTokenValue(String token, String exclude, String value)
	{
		if ( token == null ) {
			return null;
		}
		
		if ( token.equals(exclude) ) {
			return value;
		}
		
		return token;
	}
	
	/**
	 * Convert String into an integer.
	 * 
	 * @param str String to be converted.
	 * @param defValue Default value to be assigned if conversion fails.
	 * @return Integer value after conversion.
	 */
	public static int strToInt(String str, int defValue)
	{
		int value;
		
		if ( str == null ) {
			return defValue;
		}
		
		try {
			value = new Integer(str).intValue();
		} catch ( NumberFormatException ex ) {
			ex.printStackTrace();
			value = defValue;
		}
		
		return value;
	}
	
	/**
	 * Convert String into an float.
	 * 
	 * @param str String to be converted.
	 * @param defValue Default value to be assigned if conversion fails.
	 * @return float value after conversion.
	 */
	public static float strToFloat(String str, float defValue)
	{
		float value;
		
		if ( str == null ) {
			return defValue;
		}
		
		try {
			value = new Float(str).floatValue();
		} catch ( NumberFormatException ex ) {
			ex.printStackTrace();
			value = defValue;
		}
		
		return value;
	}
	
	/**
	 * Convert String into an double.
	 * 
	 * @param str String to be converted.
	 * @param defValue Default value to be assigned if conversion fails.
	 * @return double value after conversion.
	 */
	public static double strToDouble(String str, double defValue)
	{
		double value;
		
		if ( str == null ) {
			return defValue;
		}
		
		try {
			value = new Double(str).doubleValue();
		} catch ( NumberFormatException ex ) {
			ex.printStackTrace();
			value = defValue;
		}
		
		return value;
	}
}

/* end */
